package com.geohey;

import javax.servlet.ServletContextEvent;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AppContext {

	private static Logger logger = LoggerFactory.getLogger(AppContext.class);

	private static AppContext instance = new AppContext();

	private String rootDir;
	private PropertiesConfiguration appConfig;

	private AppContext() {
	}

	public static AppContext getInstance() {
		return instance;
	}

	public void init(ServletContextEvent e) {
		// 获取应用在服务器上根目录
		if (e != null) {
			rootDir = e.getServletContext().getRealPath("/");
			logger.info("根目录为'{}'", rootDir);
		}
		reloadAppConfig();
	}

	synchronized public void reloadAppConfig() {
		if (appConfig == null) {
			appConfig = new PropertiesConfiguration();
		} else {
			appConfig.clear();
		}
		String configFile = String.format("%s/WEB-INF/classes/app.properties",
				rootDir);
		try {
			appConfig.load(configFile);
			logger.info("读取配置文件成功");
		} catch (ConfigurationException ex) {
			return;
		}
	}

	public String getConfig(String key) {
		if (this.appConfig == null)
			return null;
		return appConfig.getString(key);
	}

	public void destroy() {

	}
}
